import { io } from "socket.io-client";
import registerEvent from "./registerEvent";
import type { Socket } from "socket.io-client";
import { getStoreItem } from "@/util/storage";
class MySocket {
  socket: Socket | null = null;
  constructor() {
    window.addEventListener("load", () => {
      const token = window.sessionStorage.getItem("token");
      if (token) {
        console.log("页面刷新重新创立链接");
        this.socketConnect();
      }
    });
  }
  close = () => this.socket && this.socket.close();
  
  // 断开Socket连接
  socketDisconnect() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
      console.log("Socket连接已断开");
    }
  }
  
  socketConnect() {
    const token = getStoreItem("token");
    const _socket = io("http://localhost:3000", {
      auth: {
        token: token || ""
      },
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
      reconnectionDelayMax: 5000,
      timeout: 20000
    });
    registerEvent(_socket);
    this.socketReconnect();
    this.socket = _socket;
  }
  handleUnload = () => {
    const token = getStoreItem("token");
    if (token) {
      if (sessionStorage.getItem("token")) {
        return;
      }
      window.sessionStorage.setItem("token", token);
    } else {
      window.sessionStorage.removeItem("token");
    }
  };
  socketReconnect() {
    window.removeEventListener("unload", this.handleUnload);
    window.addEventListener("unload", this.handleUnload);
  }
}
export default new MySocket();
